import React, { createRef, PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import { message, Select } from 'antd'
import {
 BreadcrumbBar, Logger, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import { getHashParameterByName } from '@/utils/helper'
import Tools from '@/utils/Tools'
import styles from './index.less'

const Bus = Tools.Bus

const { OperateItem } = ProTableOperate
const { Option } = Select

const status = [
  {
    key: 1,
    value: '待发布',
  },
  {
    key: 2,
    value: '已发布',
  },
  {
    key: 4,
    value: '运行中',
  },
  {
    key: 5,
    value: '成功',
  },
  {
    key: 6,
    value: '失败',
  },
  {
    key: 7,
    value: '停止',
  },
  {
    key: 9,
    value: '已归档',
  },
]

const statusObj = {
  1: {
    key: 1,
    value: '待发布',
    icon: 'icon-daiban',
    color: '#0084FF',
  },
  2: {
    key: 2,
    value: '已发布',
    icon: 'icon-yifabu',
    color: '#43A047',
  },
  4: {
    key: 4,
    value: '运行中',
    icon: 'icon-yunhangzhong_1',
    color: '#0084FF',
  },
  5: {
    key: 5,
    value: '成功',
    icon: 'icon-chenggong',
    color: '#43A047',
  },
  6: {
    key: 6,
    value: '失败',
    icon: 'icon-shibai1',
    color: '#EF5350',
  },
  7: {
    key: 7,
    value: '停止',
    icon: 'icon-weiyunhang',
    color: '#0084FF',
  },
  9: {
    key: 9,
    value: '已归档',
    icon: 'icon-guidang',
    color: '#0084FF',
  },
}

@connect(({ viewHistory }) => ({ ...viewHistory }))
class ViewHistory extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      query: {
        taskId: getHashParameterByName('id'),
        taskName: getHashParameterByName('taskName'),
        createBy: getHashParameterByName('createBy'),
      },
      executeType: '',
      taskStatus: '',
      menus: [{ name: '离线同步' }, { name: '历史任务' }],
      columns: [
        {
          title: '任务名称', width: '15%', dataIndex: 'taskName', key: 'taskName', ellipsis: true,
        },
        {
          title: '任务状态',
          width: '10%',
          dataIndex: 'taskStatus',
          key: 'taskStatus',
          ellipsis: true,
          render: (text, record) => <span> <i style={{ color: statusObj?.[text]?.color }} className={`iconfont ${statusObj?.[text]?.icon}`} /> {statusObj?.[text]?.value}</span>,
        },
        {
          title: '任务类型',
          width: '15%',
          dataIndex: 'executeType',
          key: 'executeType',
          ellipsis: true,
          render: (text, record) => <span>{['周期任务', '手动任务'][text]}</span>,
        },
        {
          title: '开始时间', width: '15%', dataIndex: 'startTime', key: 'startTime', ellipsis: true,
        },
        {
          title: '结束时间', width: '15%', dataIndex: 'endTime', key: 'endTime', ellipsis: true,
        },
        {
          title: '执行时长（秒）', width: '15%', dataIndex: 'duration', key: 'duration', ellipsis: true,
        },
        {
          title: '责任人', width: '10%', dataIndex: 'creator', key: 'creator', ellipsis: true,
        },
        {
          title: '操作',
          // dataIndex: 'action',
          // key: 'action',
          width: '15%',
          ellipsis: true,
          render: (text, record) => (
            <ProTableOptions size={4}>
              <span onClick={() => {
                this.setState({
                  loggerList: [],
                })
                Bus.emit('iconUpFn2')
                this.viewLog(record?.id, this.state.offsets, false)
              }}
              >
                查看日志
              </span>
              {(record?.taskStatus === 4 || null) && <span onClick={() => { this.handleOperateItem(record?.id) }}>停止</span>}
              {
                (record?.ignored !== 1 && record?.taskStatus !== 4) && (
                  <span onClick={() => {
                    this.queryIgnore([record?.id])
                  }}
                  >
                    归档
                  </span>
                )
              }
              {
                (record?.ignored === 1) && (
                  <span>
                    已归档
                  </span>
                )
              }
            </ProTableOptions>
          ),
        },
      ],
      loggerList: [],
      loading: false,
      forceUpdate: 0,
    }
    this.tableRef = createRef()
  }

  // 归档任务
  queryIgnore = (idsArr) => {
    let idsStr = ''
    idsArr.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })
    this.setState({
      loading: true,
    })
    this.props.dispatch({
      type: 'viewHistory/queryIgnore',
      params: {
        ids: idsStr,
      },
      cb: (res) => {
        const { msg } = res || {}

        // 后端需要2s的延时执行
        setTimeout(() => {
          this.setState({
            loading: false,
          })
          if (res?.status === 200) {
            message.success('操作成功')
            this.forceUpdateFn()
          } else {
            message.error(msg || '系统异常，请稍后重试~')
          }
        }, 2000)
      },
    })
  }

  forceUpdateFn = () => {
    const { query, taskStatus, executeType } = this.state
    this.tableRef?.current?.resetPageNum()
    this.setState({
      query: {
        ...query,
        executeType: executeType || '',
        taskStatus: taskStatus || '',
      },
    })
  }

  // 查看日志
  viewLog = (logId, offsets, bool) => {
    clearInterval(this.time)
    this.setState({
      loading: true,
    })
    this.props.dispatch({
      type: 'viewHistory/queryLog',
      params: {
        logId,
        offset: offsets || 0, // 参考老版本，传了固定值
      },
      cb: (res) => {
        const { status: resStatus, msg, data } = res || {}
        this.setState({
          loading: false,
        })
        if (resStatus === 200) {
          this.setState((prevState) => ({
            loggerList: prevState.loggerList.concat(data?.logContent),
          }))
          this.time = setInterval(() => {
            if (data?.logEnd && bool) {
              clearInterval(this.time)
            } else if (data?.logEnd) {
              clearInterval(this.time)
            } else {
              this.fetchLogger(logId, data?.offset, bool)
            }
          }, 4000)
        } else {
          message.error(msg || '系统异常，请稍后重试~')
        }
      },
    })
  }

  handleOperateItem = (logId) => {
    this.setState({
      loading: true,
    })

    this.props.dispatch({
      type: 'viewHistory/queryStop',
      params: {
        logId,
      },
      cb: (res) => {
        const { msg, status: resStatus } = res
        this.setState({
          loading: false,
        })
        if (resStatus === 200) {
          message.success('操作成功')
          this.setState((prevState) => ({
            forceUpdate: prevState.forceUpdate + 1,
          }))
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  render() {
    const {
      query, executeType, taskStatus, menus, loggerList, loading, forceUpdate,
    } = this.state
    const urlType = getHashParameterByName('type')
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i onClick={() => { history.push(`/dataIntegrate/apiGather/${urlType === 'http' ? 'http' : 'webService'}`) }} className="iconfont icon-zuo" />
          <span onClick={() => { history.push(`/dataIntegrate/apiGather/${urlType === 'http' ? 'http' : 'webService'}`) }}>历史任务</span>
        </div>
        <div className={styles.page_content_column}>
          <div className={`${styles.page_content_right} ${styles.page_content_right_flex}`}>
            <ProTableOperate style={{ marginBottom: 12 }}>
              <OperateItem>
                <span>任务状态</span>
                <Select
                  allowClear
                  placeholder="请选择任务状态"
                  onChange={(value) => {
                    this.setState({
                      taskStatus: value,
                    }, () => {
                      this.tableRef?.current?.resetPageNum()
                      this.setState({
                        query: {
                          ...query,
                          executeType: executeType || '',
                          taskStatus: value || '',
                        },
                      })
                    })
                  }}
                >
                  {status.map((item) => <Option value={item.key} key={item.key}>{item.value}</Option>)}
                </Select>
              </OperateItem>
              <OperateItem>
                <span>任务类型</span>
                <Select
                  allowClear
                  placeholder="请选择任务类型"
                  onChange={(value) => {
                    this.setState({
                      executeType: value,
                    }, () => {
                      this.tableRef?.current?.resetPageNum()
                      this.setState({
                        query: {
                          ...query,
                          executeType: value || '',
                          taskStatus: taskStatus || '',
                        },
                      })
                    })
                  }}
                >
                  <Option value={0} key={0}>周期任务</Option>
                  <Option value={1} key={1}>手动任务</Option>
                </Select>
              </OperateItem>
            </ProTableOperate>
            <ProTable
              key={forceUpdate}
              loading={loading}
              ref={this.tableRef}
              rowKey="id"
              columns={this.state.columns}
              query={query}
              border={false}
              url="/api/v1/integration/api/http/history"
            />
          </div>
          <Logger
            list={loggerList || []}
            // hide={hide}
            // url={id ? `/api/v1/xxl/joblog/logDetailPage?id=${id}` : null}
          // ref={(div) => (this.Logger = div)}
          />
        </div>
      </div>
    )
  }
}

export default ViewHistory
